import { Button, Form, Input, message, Select, Switch, TreeSelect } from 'antd'
import React, { useEffect, useState } from 'react'
import { fetchRequest } from "../../../utils/Request";
import { url } from "../../../utils/url";
import { Store } from 'rc-field-form/lib/interface';
import { useRequest } from "@umijs/hooks";
import { getSecretString } from "../../../utils/encrypt";

export default function ModifyEquipment(props: any) {

    interface SearchParam {
        "index": number,
        "len": number,
        "orzName": String
    }

    interface ModifyParam {
        "deviceID": String,
        "modelID": number,
        "deviceCode": String,
        "attrIDs": number[],
        "devName": String,
        "devLocation": String,
        "orzID": String
    }

    const layout = {
        labelCol: { span: 4 },
        wrapperCol: { span: 20 },
    };
    const tailLayout = {
        wrapperCol: { offset: 5, span: 14 },
    };

    const [form] = Form.useForm()

    const { Option } = Select;

    //搜索公司状态
    const [orzList, setOrzList] = useState<any>([]);
    const [devAttrList, setDevAttrList] = useState<any>([]);
    const [devTypeList, setDevTypeList] = useState<any>([]);
    const orzOptions = orzList.map((d: any, index: number) => <Option value={d.label} key={index}>{d.value}</Option>);
    const attrOptions = devAttrList.map((d: any, index: number) => <Option value={d.label} key={index} disabled={d.disable}>{d.value}</Option>);
    const typeOptions = devTypeList.map((d: any, index: number) => <Option value={d.value} key={index}>{d.title}</Option>);
    const[boxDevdeviceMac,setBoxDevdeviceMac] = useState<boolean>(props.content.devAttrIDs.indexOf(9)!== -1 ? true:false);
    const deviceMacVisible = {
        display:boxDevdeviceMac ? '':'none' 
    }
    useEffect(() => {
        getDevTypeRequest();
        setOrzList([{ label: props.content.orzID, value: props.content.orzName }]);
    
    }, []);
    //搜索公司
    async function searchOrzRequest(params: SearchParam) {

        try {
            const json = await fetchRequest(url.SEARCH_ORZ, params);
            if (json.success) {
                setOrzList(json.data);
            } else {
                message.destroy();
                message.error(json.error)
            }
        } catch (error: any) {
            message.destroy();
            message.error(error.message)
        }
    }

    const searchOrz = useRequest(searchOrzRequest, {
        manual: true,
        loadingDelay: 200
    });
    
    //获取设备属性
    async function getDevAttrRequest(params:any) {

        try {
            const json = await fetchRequest(url.GET_ATTRBYMODEI,params);
            if (json.success) {
                let devAttrListTemp = json.data;
                for (let i = 0; i < devAttrListTemp.length; i++) {
                    devAttrListTemp[i].disable = false;
                }
                // console.log(devAttrListTemp)
                setDevAttrList(devAttrListTemp);
                // console.log(props.content.devAttrIDs)
                initialAttrSelect(props.content.devAttrIDs, devAttrListTemp);
            } else {
                message.destroy();
                message.error(json.error)
            }
        } catch (error: any) {
            message.destroy();
            message.error(error.message)
        }
    }

    const getDevAttr = useRequest(getDevAttrRequest, {
        manual: true,
        loadingDelay: 200
    });

    //获取设备类型
    async function getDevTypeRequest() {

        try {
            const json = await fetchRequest(url.GET_DEV_TYPE, "");
            if (json.success) {
                setDevTypeList(json.data[0].children)
                getDevAttr.run({deviceModelID:json.data[0].children?.find((item:any)=>  item.title === props.content.deviceModel )?.value})
            } else {
                message.destroy();
                message.error(json.error)
            }
        } catch (error: any) {
            message.destroy();
            message.error(error.message)
        }
    }

    const getDevType = useRequest(getDevTypeRequest, {
        manual: true,
        loadingDelay: 200
    });

    //修改设备
    async function modifyDevRequest(params: ModifyParam) {

        try {
            const json = await fetchRequest(url.ADD_MODIFY_DE, params);
            if (json.success) {
                message.destroy();
                message.success("修改成功！");
                props.onModifySuccess();
            } else {
                message.destroy();
                message.error(json.error)
            }
        } catch (error: any) {
            message.destroy();
            message.error(error.message)
        }
    }

    const modifyDev = useRequest(modifyDevRequest, {
        manual: true,
        loadingDelay: 200
    });


    function handleChange(value: string) {
        // console.log(value)
    }
    function attrOnChange(value:any) {
        const devAttrListTemp =[...devAttrList];
        setBoxDevdeviceMac(false)
        for(let m=0;m<devAttrListTemp.length;m++){
                devAttrListTemp[m].disable=false;
        }
        if(value.indexOf(1) !== -1 || value.indexOf(9) !== -1){
            value.indexOf(9)!== -1 && setBoxDevdeviceMac(true)
            for(let j=0;j<devAttrListTemp.length;j++){
                if(devAttrListTemp[j].label===2 ){
                    devAttrListTemp[j].disable=true;
                }
            }
        }else if(value.indexOf(2) !== -1){
            for(let j=0;j<devAttrListTemp.length;j++){
                if(devAttrListTemp[j].label===1 ){
                    devAttrListTemp[j].disable=true;
                }
                if(devAttrListTemp[j].label===9 ){
                    devAttrListTemp[j].disable=true;
                }
            }
        }
        setDevAttrList(devAttrListTemp);
    }
    function initialAttrSelect(value: any, attrList: any) {

        let devAttrListTemp = attrList;

        for (let j = 0; j < devAttrListTemp.length; j++) {
            devAttrListTemp[j].disable = false;
        }
        if (value.indexOf(1) !== -1) {
            for (let j = 0; j < devAttrListTemp.length; j++) {
                if (devAttrListTemp[j].label === 2) {
                    devAttrListTemp[j].disable = true;
                }
            }
        } else if (value.indexOf(2) !== -1) {
            for (let j = 0; j < devAttrListTemp.length; j++) {
                if (devAttrListTemp[j].label === 1) {
                    devAttrListTemp[j].disable = true;
                }
            }
        }

        setDevAttrList(devAttrListTemp);

    }

    //搜索
    function search(value: string) {
        // console.log(value);
        if (value === "" || value === undefined) {
            return
        }
        const params: SearchParam = { index: 0, len: 100, orzName: value };
        searchOrz.run(params);
    }

    function onFinish(value: Store) {

        // console.log(props.content.deviceID)
        // console.log(value)

        // const data: { "roleID": string; "authID": string; }[] = []
        // value.roleAuth.map((item: string) => {
        //     const temp = item.split("-");
        //     if (temp.length > 1)
        //         data.push({ "roleID": temp[0], "authID": temp[1] })
        // })
        //
        const params = {
            deviceID: props.content.deviceID,
            modelID: value.devType,
            deviceCode: value.devCode,
            attrIDs: value.devAttr,
            devName: value.devName,
            devLocation: value.devLocation,
            orzID: value.dept,
            boxDevSerial:value.boxDevSerial,
            collegeAreaId:props.content.collegeAreaId,
            deviceModelID:props.content.devModelID,
            deviceMac:value.deviceMac
        }
        
        modifyDev.run(params)
    }

    return (
        <Form form={form} {...layout} onFinish={onFinish} initialValues={{
            devCode: props.content.deviceCode, devName: props.content.devName,boxDevSerial:props.content.deviceCode,deviceMac:props.content.deviceMac,
            devType: props.content.deviceModel, devAttr: props.content.devAttrIDs, dept: props.content.allAddress, devLocation: props.content.devLocation
        }}>
            <Form.Item label="设备编码" name="devCode" rules={[{ required: true, message: "必须要输入设备编码!" }]}>
                <Input disabled />
            </Form.Item>

            <Form.Item label="设备名称" name="devName" rules={[{ required: true, message: "必须要输入设备名称!" }]}>
                <Input />
            </Form.Item>

            <Form.Item label="设备类型" name="devType" rules={[{ required: true, message: "必须要选择设备类型!" }]}>
                <Select
                    disabled
                    style={{ width: '100%' }}
                    placeholder="请选择设备类型"
                >
                    {typeOptions}
                </Select>
            </Form.Item>
            <Form.Item label="厂家出场序列号" name="boxDevSerial" rules={[{ required: true, message: "必须要输入设备编码!" }]}>
                <Input disabled />
            </Form.Item>
            <Form.Item label="设备属性" name="devAttr" rules={[{ required: true, message: "必须要选择设备属性!" }]}>
                <Select
                    mode="multiple"
                    style={{ width: '100%' }}
                    placeholder="请选择设备属性"
                    onChange={attrOnChange}
                >
                    {attrOptions}
                </Select>
            </Form.Item>
            <Form.Item label="设备Mac编号" name="deviceMac" style={deviceMacVisible} rules={[{ required: boxDevdeviceMac, message: "必须要输入设备Mac编号!" }]}>
                <Input placeholder="请输入设备Mac编号" disabled={props.content.deviceMac?true:false}/>
            </Form.Item>
            <Form.Item label="设配地址" name="dept" rules={[{ required: true, message: "必须要选择设配地址！" }]}>
                <Select
                    showSearch
                    disabled
                    // value={this.state.value}
                    placeholder="请选择设配地址"
                    // style={this.props.style}
                    defaultActiveFirstOption={false}
                    showArrow={false}
                    filterOption={false}
                    onSearch={search}
                    onChange={handleChange}
                // notFoundContent={null}
                >
                    {orzOptions}
                </Select>
            </Form.Item>

            <Form.Item label="设备位置描述" name="devLocation" rules={[{ required: true, message: "必须要输入设备位置描述!" }]}>
                <Input />
            </Form.Item>

            <Form.Item {...tailLayout}>
                <Button type="primary" htmlType="submit" loading={modifyDev.loading}>提交</Button>
            </Form.Item>


        </Form>
    )
}
